#include <REGX52.H>
#include <INTRINS.H>

#define uchar unsigned char
#define uint unsigned int
#define ulong unsigned long

unsigned char led_data[]={
	0x3F,  //"0"
    0x06,  //"1"
    0x5B,  //"2"
    0x4F,  //"3"
    0x66,  //"4"
    0x6D,  //"5"
    0x7D,  //"6"
    0x07,  //"7"
    0x7F,  //"8"
    0x6F,  //"9"
};

void Delay1ms()	;
void Delay(int t);
void show(ulong digit);
void show_digit(uchar pos, uchar digit);

void main()
{
    ulong digit = 0;

     while(1){

        if(0 == P3_1){

            Delay(10);

            while(0 == P3_1){
                //nop
            }
            Delay(10);  
            
            if(digit<99999999)
            {
                digit++;
            }else{
                digit = 0;
            }
            
            
        }
        else if(0 == P3_0){
            Delay(10);

            while(0 == P3_0){
                //nop
            }
            Delay(10);  
            
            if(digit>0)
            {
                digit--;
            }else{
                digit = 99999999;
            }
        }


        show(digit);

    }
}


void Delay1ms()		//@11.0592MHz
{
	unsigned char i, j;

	_nop_();
	i = 2;
	j = 199;
	do
	{
		while (--j);
	} while (--i);
}

void Delay(int t){
    int i = 0;
    for(i=0;i<t;i++){
        Delay1ms();
    }
}

void show(ulong digit)
{
    unsigned char pos = 0;
    do
    {
        show_digit(pos,digit%10);
        digit/=10;
        pos++;
    }while(digit);
}

void show_digit(uchar pos, uchar digit)
{
    static uchar pos_map[][3] = {{0,0,0},{0,0,1},{0,1,0},{0,1,1},
                                {1,0,0},{1,0,1},{1,1,0},{1,1,1}};

    pos %= 8;
    P2_2 = pos_map[pos][2];
    P2_3 = pos_map[pos][1];
    P2_4 = pos_map[pos][0];

    digit %= 10;
    P0 = led_data[digit];
    Delay1ms();
    P0 = 0;//clear
}